package com.kantboot.redis.session.http;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class KantbootRedisSession {

    /** key 前缀 */
    private static final String PREFIX_NAME = "SESSION_ID:";

    /** 获取的请求头 */
    private static final String REQUEST_HEADER = "SESSION_ID";

    /**
     *
     * @param keyName key名，如`user`、`authz`、`user_id`
     * @param request
     * @return
     */
    public static String toKey(String keyName,HttpServletRequest request){
        return PREFIX_NAME + request.getHeader(REQUEST_HEADER)+":"+keyName;
    }

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 获取Session_id
     * @param request
     * @return
     */
    public String getSessionId(HttpServletRequest request){
        return request.getHeader(REQUEST_HEADER);
    }

    public <T> T getAttribute(String keyName,Class<T> clazz,HttpServletRequest request){
        ValueOperations ops = redisTemplate.opsForValue();
        log.info(ops.get(toKey(keyName,request)).toString());
        return  JSON.parseObject(
                (ops.get(toKey(keyName,request)).toString())
                ,clazz);
    }


    /**
     * 新增存储
     * @param keyName
     * @param var
     * @param request
     */
    public void setAttribute(String keyName, Object var,HttpServletRequest request){
        ValueOperations ops = redisTemplate.opsForValue();
        String key = KantbootRedisSession.toKey(keyName,request);

        if(var instanceof String){
            ops.set(key,var.toString());
            return;
        }

        if(var instanceof Integer || var instanceof Double || var instanceof Float){
            ops.set(key,var);
            return;
        }

        ops.set(key, JSON.toJSONString(var),60*24*7, TimeUnit.SECONDS);

    }

    /**
     * 删除存储
     * @param keyName
     * @param var
     * @param request
     */
    public void removeAttribute(String keyName, Object var,HttpServletRequest request){
        String key = KantbootRedisSession.toKey(keyName,request);
        redisTemplate.delete(key);
    }

}
